import type { CSSProperties, ReactNode } from "react";
import React from "react";
import { cn } from "@/common/cn";

type ListProps<T> = {
  header?: ReactNode | undefined;
  footer?: ReactNode | undefined;
  bordered?: boolean | undefined;
  dataSource?: T[] | undefined;
  renderItem?: (item: T, index: number) => ReactNode | undefined;
  className?: string | undefined;
  style?: CSSProperties | undefined;
  rowKey?: (item: T) => React.Key;
};

export default function List<T>(p: ListProps<T>) {
  const borderClass = p.bordered && "border border-gray-300 rounded-md shadow-sm";

  return (
    <div className={cn("w-full", borderClass, p.className)} style={p.style}>
      {p.header && <div className="px-4 py-3 border-b border-gray-200">{p.header}</div>}
      <div>
        <ul className="divide-y divide-gray-200">
          {p.dataSource?.map((item, index) => (
            <React.Fragment key={p.rowKey?.(item)}>{p.renderItem?.(item, index)}</React.Fragment>
          ))}
        </ul>
      </div>
      {p.footer && <div className="px-4 py-3 border-t border-gray-200">{p.footer}</div>}
    </div>
  );
}

type ListItemProps = React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>;

export function ListItem({ className, ...r }: ListItemProps) {
  return <li className={cn("py-2 px-4 hover:bg-gray-50 cursor-pointer", className)} {...r} />;
}
